package com.small.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.small.common.Const;
import com.small.common.ResponseCode;
import com.small.common.ServerResponse;
import com.small.dao.CategoryMapper;
import com.small.dao.ProductMapper;
import com.small.pojo.Category;
import com.small.pojo.Product;
import com.small.service.ICategoryService;
import com.small.service.IProductService;
import com.small.util.DateTimeUtil;
import com.small.util.PropertiesUtil;
import com.small.vo.ProductDetailVo;
import com.small.vo.ProductListVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: small
 * @description:
 * @author: Mr.Xie
 * @create: 2019-04-25 08:56
 */
@Service("iProductService")
public class ProductServiceImpl implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ICategoryService iCategoryService;

    /**
     * 更新或新增商品
     */
    public ServerResponse saveOrUpdateProduct(Product product) {
        if (product != null) {
            if (StringUtils.isNotBlank(product.getSubImages())) {
                String[] subImageArray = product.getSubImages().split(",");
                if (subImageArray.length > 0) {
                    product.setMainImage(subImageArray[0]);
                }
            }
            if (product.getId() != null) {
                int rowCount = productMapper.updateByPrimaryKey(product);
                if (rowCount > 0) {
                    return ServerResponse.createBySuccessMessage("更新产品成功");
                }
                return ServerResponse.createBySuccessMessage("更新产品失败");
            } else {
                int rowCount = productMapper.insert(product);
                if (rowCount > 0) {
                    return ServerResponse.createBySuccessMessage("新增产品成功");
                }
                return ServerResponse.createBySuccessMessage("新增产品失败");
            }
        }
        return ServerResponse.createByErrorMessage("产品参数不正确");
    }

    /**
     * 修改商品销售状态
     */
    public ServerResponse<String> setSaleStatus(Integer productId, Integer status) {
        if (productId == null || status == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        //修改成根据请求发送的商品id和要修改的状态码
        Product product = new Product();
        product.setId(productId);
        product.setStatus(status);
        int rowCount = productMapper.updateByPrimaryKeySelective(product);
        if (rowCount > 0) {
            return ServerResponse.createBySuccessMessage("修改产品销售状态成功");
        }
        return ServerResponse.createByErrorMessage("修改产品销售状态失败");
    }

    //商品详细信息
    public ServerResponse<ProductDetailVo> manageProductDetail(Integer productId) {
        if (productId == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Product product = productMapper.selectByPrimaryKey(productId);
        if (product == null) {
            return ServerResponse.createByErrorMessage("产品已下架");
        }
        //包装vo
        ProductDetailVo productDetailVo = assembleProductDetailVO(product);
        return ServerResponse.createBySuccess(productDetailVo);
    }

    private ProductDetailVo assembleProductDetailVO(Product product) {
        //添加前台需要的字段进行包装
        ProductDetailVo productDetailVo = new ProductDetailVo();
//        productDetailVo.setId(product.getId());
//        productDetailVo.setSubtitle(product.getSubtitle());
//        productDetailVo.setCategoryId(product.getCategoryId());
//        productDetailVo.setName(product.getName());
//        productDetailVo.setMainImage(product.getMainImage());
//        productDetailVo.setPrice(product.getPrice());
//        productDetailVo.setStatus(product.getStatus());
        BeanUtils.copyProperties(product, productDetailVo);
        //图片服务器路径
        productDetailVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix", "http://img.happymmall.com/"));
        Category category = categoryMapper.selectByPrimaryKey(product.getCategoryId());
        if (category == null) {
            productDetailVo.setParentCategoryId(0);//默认根节点
        } else {
            productDetailVo.setParentCategoryId(category.getParentId());
        }
        //时间类型转换
        productDetailVo.setCreateTime(DateTimeUtil.dateToStr(product.getCreateTime()));
        productDetailVo.setUpdateTime(DateTimeUtil.dateToStr(product.getUpdateTime()));

        return productDetailVo;
    }

    //商品分页
    public ServerResponse getProductList(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        //查询所有商品
        List<Product> productList = productMapper.selectList();
        //转换为前台的vo
        List<ProductListVo> listVos = Lists.newArrayList();
        for (Product pr : productList) {
            ProductListVo productListVo = assembleProductListVo(pr);
            listVos.add(productListVo);
        }
        //原始数据分页
        PageInfo pageInfo = new PageInfo(productList);
        //显示vo数据
        pageInfo.setList(listVos);
        return ServerResponse.createBySuccess(pageInfo);
    }

    /**
     * @Param:
     * @return: ProductListVo 转换后前台显示的vo数据
     */
    private ProductListVo assembleProductListVo(Product product) {
        ProductListVo productListVo = new ProductListVo();
        BeanUtils.copyProperties(product, productListVo);
        productListVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix", "http://image.imooc.com/"));
        return productListVo;
    }

    /**
     * @Param:
     * @return: 根据商品名称和id查询
     */
    public ServerResponse<PageInfo> searchProduct(String productName, Integer productId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        if (StringUtils.isNotBlank(productName)) {
            //根据名称模糊查询，名称拼串加上%%
            productName = new StringBuilder().append("%").append(productName).append("%").toString();
        }
        //模糊查询出原始数据
        List<Product> productList = productMapper.selectByNameAndProductId(productName, productId);
        //包装前台显示vo数据
        List<ProductListVo> listVos = Lists.newArrayList();
        for (Product pr : productList) {
            ProductListVo productListVo = assembleProductListVo(pr);
            listVos.add(productListVo);
        }
        //用原始数据分页
        PageInfo pageInfo = new PageInfo(productList);
        //显示vo数据
        pageInfo.setList(listVos);
        return ServerResponse.createBySuccess(pageInfo);
    }

    //查询商品信息
    public ServerResponse<ProductDetailVo> getProductDetail(Integer productId) {
        if (productId == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Product product = productMapper.selectByPrimaryKey(productId);
        if (product == null) {
            return ServerResponse.createByErrorMessage("产品已下架");
        }
        if (product.getStatus() != Const.ProductStatusEnum.ON_SALE.getCode()) {
            return ServerResponse.createByErrorMessage("产品已下架");
        }
        //包装vo
        ProductDetailVo productDetailVo = assembleProductDetailVO(product);
        return ServerResponse.createBySuccess(productDetailVo);
    }

    public ServerResponse<PageInfo> getProductByKeywordCategory(String keyword, Integer categoryId, int pageNum, int pageSize, String orderBy) {
        if (StringUtils.isBlank(keyword) && categoryId == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        List<Integer> categoryIdList = new ArrayList<>();
        if (categoryId != null) {
            //根据商品分类id查询
            Category category = categoryMapper.selectByPrimaryKey(categoryId);
            if (category == null && StringUtils.isBlank(keyword)) {
                //没有该分类，并且没有关键字，返回一个空的结果集，不报错
                PageHelper.startPage(pageNum, pageSize);
                List<ProductListVo> productListVos = Lists.newArrayList();
                PageInfo pageInfo = new PageInfo(productListVos);
                //没有任何信息 返回一个空的分页
                return ServerResponse.createBySuccess(pageInfo);
            }
            //该分类id所有子节点
            categoryIdList = iCategoryService.selectCategoryAndChildrenById(categoryId).getData();
        }
        //有关键字就设置模糊查询
        if (StringUtils.isNotBlank(keyword)) {
            keyword = "%" + keyword + "%";
        }
        PageHelper.startPage(pageNum, pageSize);
        //排序处理
        if (StringUtils.isNotBlank(orderBy)) {
            if (Const.ProductListOrderBy.PRICE_ASC_DESC.contains(orderBy)) {
                //前台传入的排序规则比如price_desc
                String[] orderByArray = orderBy.split("_");
                //          根据 ：   price               desc       排序
                PageHelper.orderBy(orderByArray[0] + " " + orderByArray[1]);
            }
        }
        //根据关键字和分类下的子节点id查询列表
        List<Product> productList = productMapper.selectByNameAndCategoryIds(StringUtils.isBlank(keyword) ? null : keyword, categoryIdList.size() == 0 ? null : categoryIdList);
        List<ProductListVo> productListVos = Lists.newArrayList();
        for (Product product : productList) {
            //查询结果转换成vo
            ProductListVo productListVo = assembleProductListVo(product);
            productListVos.add(productListVo);
        }
        //原始数据分页
        PageInfo pageInfo = new PageInfo(productList);
        //vo数据显示
        pageInfo.setList(productListVos);
        return ServerResponse.createBySuccess(pageInfo);
    }
}
